package com.huizhonglm.diap.core.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.huizhonglm.diap.DiapApplication;

import java.util.Locale;
import java.util.TimeZone;

/**
 * 设备工具类
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-02 10:12
 */
public class DeviceUtil {

    /**
     * 当前手机时区名称。如：GMT+0800
     *
     * @return 时区名称
     */
    public static String getTimeZoneName() {
        String timeZoneDisplayName = "GMT+0800";
        try {
            // GMT+0800
            timeZoneDisplayName = TimeZone.getDefault().getDisplayName(true, TimeZone.SHORT);
            long offset = TimeZone.getDefault().getRawOffset();
            int zone = (int) (offset / (60 * 60 * 1000));
            if (zone >= 0) {
                timeZoneDisplayName = String.format("GMT+%02d", Math.abs(zone));
            } else {
                timeZoneDisplayName = String.format("GMT-%02d", Math.abs(zone));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeZoneDisplayName;
    }

    /**
     * 当前手机时区编号。如：Asia/Shanghai
     *
     * @return 时区编号
     */
    public static String getTimeZoneID() {
        String timeZoneID = "Asia/Shanghai";
        try {
            // Asia/Shanghai
            timeZoneID = TimeZone.getDefault().getID();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeZoneID;
    }

    /**
     * 获取手机语言信息(例如：en、zh) <br>
     * (设置成简体中文的时候，getLanguage()返回的是zh,getCountry()返回的是cn)
     *
     * @return 手机语言
     */
    public static String getLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取手机国家信息(例如：EN、CN) <br>
     * (设置成简体中文的时候，getLanguage()返回的是zh,getCountry()返回的是cn)
     *
     * @return 手机国家
     */
    public static String getCountry() {
        // 获取区域
        return Locale.getDefault().getCountry();
    }

    /**
     * 手机唯一的标识
     *
     * @return String
     */
    public static String getIMEI() {
        TelephonyManager tm = (TelephonyManager) DiapApplication.getInstance().getContext().getSystemService(Context.TELEPHONY_SERVICE);
        String id = tm.getDeviceId();
        if (id == null)
            return "";
        else
            return id;
    }

    /**
     * 获取运营商sim卡IMSI
     *
     * @return String
     */
    public static String getIMSI() {
        try {
            TelephonyManager tm = (TelephonyManager) DiapApplication.getInstance().getContext().getSystemService(Context.TELEPHONY_SERVICE);
            String id = tm.getSubscriberId();
            if (id == null)
                return "";
            else
                return id;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取SIM卡的可用状态
     *
     * @return true:SIM可用，false:SIM不可用
     */
    public static boolean isSimActive() {
        TelephonyManager tm = (TelephonyManager) DiapApplication.getInstance().getContext().getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return false;
        }
        return TelephonyManager.SIM_STATE_READY == tm.getSimState();
    }

    /**
     * 获取手机号码
     *
     * @return
     */
    public static String getPhoneNumber() {
        try {
            TelephonyManager tm = (TelephonyManager) DiapApplication.getInstance().getContext().getSystemService(Context.TELEPHONY_SERVICE);
            return tm.getLine1Number();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 获取手机网络运营商 <BR>
     * 需要加入权限 android.permission.READ_PHONE_STATE <BR>
     * <a href="http://www.open-open.com/lib/view/open1331537862874.html"
     * >参考资料</a>
     *
     * @return 中国移动、中国联通、中国电信
     */
    public static String getNetworkOperators() {
        String strOperators = "unknown";
        String IMSI = getIMSI();
        // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。
        if (IMSI != null) {
            if (IMSI.equals("46000") || IMSI.equals("46002") || IMSI.equals("46007")) {
                strOperators = "中国移动";
            } else if (IMSI.equals("46001")) {
                strOperators = "中国联通";
            } else if (IMSI.equals("46003")) {
                strOperators = "中国电信";
            }
        }
        return strOperators;
    }

    /**
     * 获取设备ANDROID_ID
     *
     * @param context
     * @return
     */
    public static String getAndroidID(Context context) {
        try {
            return android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return "";
        }
    }



    /**
     * @return String
     * @Description: 获取手机型号
     */
    public static String getDeviceModel() {
        return android.os.Build.MODEL;
    }

    /**
     * @return String
     * @Description: 获取系统版本
     */
    public static String getOS() {
        return android.os.Build.VERSION.RELEASE;
    }



    /**
     * 获取设备是否是横屏(AndroidPad)设备
     *
     * @param context
     * @return
     * @author StoneJxn
     * @since v0.0.1
     */
    public static boolean getLandscapeDevice(Context context) {
        Activity activity = (Activity) context;
        int orientation = activity.getResources().getConfiguration().orientation;
        int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        return (orientation == Configuration.ORIENTATION_PORTRAIT && displayRotation % 2 != 0) || (orientation == Configuration.ORIENTATION_LANDSCAPE && displayRotation % 2 == 0);
    }

    /**
     * 获取用于显示的版本号(显示如：1.0.0)
     *
     * @return 版本名称
     */
    public static String getVersionName() {
        Context context = DiapApplication.getInstance().getContext();
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }

    /**
     * 获取用于升级的版本号(内部识别号)
     *
     * @return 版本号
     */
    public static int getVersionCode() {
        Context context = DiapApplication.getInstance().getContext();
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取应用程序的完整包名
     *
     * @return eg. com.xxx.xxx
     */
    public static String getPackageName() {
        return DiapApplication.getInstance().getContext().getPackageName();
    }

    /**
     * 获取App安装包信息
     *
     * @return
     */
    public PackageInfo getPackageInfo() {
        Context context = DiapApplication.getInstance().getContext();
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }

    /**
     * 判断当前版本是否兼容目标版本的方法
     *
     * @param VersionCode
     * @return
     */
    public static boolean isVersionCompat(int VersionCode) {
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    /**
     * 获取当前网络类型 <a
     * href="http://blog.csdn.net/shakespeare001/article/details/7505932"
     * >参考资料</a>
     *
     * @return
     * @author StoneJxn
     * @since v0.0.1
     */
    public static String getNetworkType(Context context) {
        String strNetworkType = "unknown";
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return strNetworkType;
        }
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            strNetworkType = "WIFI";
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            switch (networkInfo.getSubtype()) {
                case TelephonyManager.NETWORK_TYPE_CDMA:// 网络类型为CDMA
                case TelephonyManager.NETWORK_TYPE_EDGE:// 网络类型为EDGE
                case TelephonyManager.NETWORK_TYPE_GPRS:// 网络类型为GPRS
                    strNetworkType = "2G";
                    break;
                case TelephonyManager.NETWORK_TYPE_EVDO_0:// 网络类型为EVDO0
                case TelephonyManager.NETWORK_TYPE_EVDO_A:// 网络类型为EVDOA
                case TelephonyManager.NETWORK_TYPE_HSDPA:// 网络类型为HSDPA
                case TelephonyManager.NETWORK_TYPE_HSPA:// 网络类型为HSPA
                case TelephonyManager.NETWORK_TYPE_HSUPA:// 网络类型为HSUPA
                case TelephonyManager.NETWORK_TYPE_UMTS:// 网络类型为UMTS
                    strNetworkType = "3G";
                    break;
                default:
                    break;
            }
        }
        return strNetworkType;
    }

    /**
     * 获取手机mac地址(错误返回12个0 )
     *
     * @return wifi MAC
     */
    public static String getMAC() {
        Context context = DiapApplication.getInstance().getContext();
        // 获取mac地址：
        String macAddress = "000000000000";
        try {
            WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
            if (null != info) {
                if (!TextUtils.isEmpty(info.getMacAddress())) {
                    macAddress = info.getMacAddress();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return macAddress;
        }
        return macAddress;
    }

    public static void makePhoneCall(final Context con, final String tel) {
        if (tel == null || tel.equals("")) {
            ToastUtil.makeTextShort("手机号码无效");
            return;
        }
        if (isSimActive()) {
            // 客服支持
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + tel));
            con.startActivity(intent);
        } else {
            ToastUtil.makeTextShort("SIM卡无效");
        }
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static boolean GPSIsOpen(Context context) {
        LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = mgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (gps) {
            return true;
        }
        return false;
    }
}
